#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <stdbool.h>
#include <ctype.h>

typedef struct {
    char class[20];     // 班级
    char id[20];        // 学号
    char name[20];      // 姓名（可以是任意格式）
} Student;

// 硬编码的学生数据库（姓名不再限制"小X"格式）
Student students[] = {
    {"网工2403", "24403000604", "王强"},
    {"网工2403", "24403000607", "高雨晴"},
    {"网工2403", "24403000708", "李星辰"},
    // 添加更多学生...
};
#define STUDENT_COUNT (sizeof(students) / sizeof(students[0]))

// 从文件名中提取学号和非数字部分（姓名）
void extract_parts(const char *filename, char *id, char *name_part) {
    int i = 0, j = 0;
    bool in_number = false;

    id[0] = '\0';
    name_part[0] = '\0';

    while (filename[i] != '\0') {
        if (isdigit(filename[i])) {
            if (!in_number) {
                in_number = true;
                j = 0;
            }
            id[j++] = filename[i];
        } else {
            if (in_number) {
                id[j] = '\0';
                in_number = false;
                j = 0;
            }
            name_part[j++] = filename[i];
        }
        i++;
    }
    if (in_number) id[j] = '\0';
    name_part[j] = '\0';
}

// 根据学号或姓名片段匹配学生
const Student* find_student(const char *id, const char *name_part) {
    for (int i = 0; i < STUDENT_COUNT; i++) {
        // 优先用学号匹配
        if (id != NULL && strstr(students[i].id, id) != NULL) {
            return &students[i];
        }
        // 其次用姓名片段匹配
        if (name_part != NULL && strstr(students[i].name, name_part) != NULL) {
            return &students[i];
        }
    }
    return NULL;
}

void rename_file(const char *old_name, const Student *student) {
    char new_name[100];
    snprintf(new_name, sizeof(new_name), "%s-%s-%s.zip", 
             student->class, student->id, student->name);
    
    if (rename(old_name, new_name) == 0) {
        printf("Renamed: %s -> %s\n", old_name, new_name);
    } else {
        perror("Rename failed");
    }
}

int main() {
    DIR *dir = opendir(".");
    if (!dir) {
        perror("Cannot open directory");
        return 1;
    }

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        if (strstr(entry->d_name, ".zip")) {
            char id[20] = {0};
            char name_part[100] = {0};
            
            extract_parts(entry->d_name, id, name_part);
            
            const Student *student = find_student(
                strlen(id) > 0 ? id : NULL,
                strlen(name_part) > 0 ? name_part : NULL
            );

            if (student) {
                rename_file(entry->d_name, student);
            } else {
                printf("No match for: %s (ID: %s, NamePart: %s)\n", 
                       entry->d_name, id, name_part);
            }
        }
    }

    closedir(dir);
    return 0;
}